/*
* @Desc 编辑模板
* @Auth Sang
* @Date 2015-09-28 15:50:31
**/

var prevElm;
var base_add_btn;
var $frame;
var framePath;
$(function(){
	var modMaskTpl = $('#mod_mask');
	
	// 框架加载完成后触发
	$('#page_view_frame').load(function(){
		$frame = $(window.frames['page_view_frame'].document);
		framePath = window.frames['page_view_frame'].location.pathname;
		//body上边空20px 才能看到编辑的按钮
		$('<style>body{padding-top: 20px !important;}.mod_mask .fa{cursor:pointer;color:#aaaaaa;margin-right:7px}.mod_mask .fa:hover{color:#eeeeee;}</style>').appendTo($frame.find('head'));
		$frame.find('a').attr('href','javascript:;');
		$wrapper = $frame.find('.mods');
		if($wrapper.length==0){
			return;
		}
		$modules = $wrapper.find('.mod');
		if($modules.length==0){
			addAddBtn(framePath);
		}else{
			$modules.css({'minHeight':30});
			$modules.each(function(i,o){
				addMask(o);
			});
		}
		// 注册遮罩层的按钮点击事件
		$frame.on('click', '.mod_mask .fa', function(e) {
			e.preventDefault();
			var mod = $(this).parent().parent().parent();
			var length = $modules.length;
			switch(true){
				// 添加模块
				case $(this).hasClass('fa-plus'):
					return showModuleChoolsBox.call(mod,framePath);
					break;
				// 调整位置
				case $(this).hasClass('fa-arrow-up'):
				case $(this).hasClass('fa-arrow-down'):
					return modSort(mod,$(this).attr('class').split(' ')[1].split('-')[2]);
					break;
				// 删除模块
				case $(this).hasClass('fa-trash'):
					removeMod(mod,function(){
						if($wrapper.find('.mod').length==0){
							addAddBtn(framePath);
						}
					});
					break;
				// 配置模块
				case $(this).hasClass('fa-cog'):
					config(mod);
					break;

			}
		});

		$frame.on('mouseenter','.mod',function(e) {
			var index = $frame.find('.mod').index(this);
			var modMask = $(this).find('.mod_mask');
			if(modMask.length==0){
				addMask($(this));
				modMask = $(this).find('.mod_mask');
			}
			if(index==0){
				modMask.find('.fa-arrow-up').hide();
			}else{
				modMask.find('.fa-arrow-up').show();
			}
			if(index==$frame.find('.mod').length-1){
				modMask.find('.fa-arrow-down').hide();
			}else{
				modMask.find('.fa-arrow-down').show();
			}
			modMask.show();
		}).on('mouseleave','.mod',function(e) {
			$(this).find('.mod_mask').hide();
		});
	});
	
	function addAddBtn(framePath){
		base_add_btn = $('<div style="width:98%;border:1px solid #cccccc;background:#efefef;color:#999999;text-align:center;height:50px;margin:5px auto;line-height:50px;font-size:14px;cursor:pointer">+添加模块</div>');
		base_add_btn.click(function(){
			showModuleChoolsBox.call(this,framePath);
		});
		$frame.find('.mods').append(base_add_btn);
	}

	// 注册编辑框按钮事件
	$('#config-contail .config-btns').on('click', 'input', function(e) {
		e.preventDefault();
		switch(this.id){
			case 'submit':
				var data = $('#config-contail .config-form form').serialize();
				$.ajax({
					url: '/tplConfig/configWidget',
					type: 'POST',
					dataType: 'JSON',
					data: data,
					success:function(result){
						alert(result.msg);
					}
				})
				break;
			case 'close':
				$('#config-contail').hide();
				break;
		}
	});
});

function showModuleChoolsBox(framePath){
	window.prevElm = $(this).hasClass('mod') ? $(this) : null;
	var url = '/tplConfig/showWidgets?page='+framePath;
	General.extendDialog(); //扩展对话框
	General.showDialogWidthHeight('选择模块(挂件)',url,'90%',0);
}

function modSort(curSeletor,direction){
	switch(direction){
		case 'up':
			var prev = $(curSeletor).prev();
			if(prev.length>0){
				prev.before($(curSeletor).clone());
				$(curSeletor).remove();
			}
			afterModSort($(curSeletor),prev);
			break;
		case 'down':
			var next = $(curSeletor).next();
			if(next.length>0){
				next.after($(curSeletor).clone());
				$(curSeletor).remove();
			}
			afterModSort($(curSeletor),next);
			break;
	}
}

function afterModSort(el,tagEl){
	var elUinqid = el.attr('data-uniqid'),
		tagUniqid = tagEl.attr('data-uniqid');
	$.post('/tplConfig/switchWidget/update',{
		cur_uniqid:elUinqid,
		tag_uniqid:tagUniqid
	});
}

function addWidget(id,tag,page_id){
	if(!id || !tag){
		alert('invalid id|tag');
		General.closeDialog();
	}else{
		$.post('/tplConfig/showWidgetContent?id='+id+'&theme='+THEME+'&page='+framePath, {}, function(data){
			console.log(data)
			if(data.error){
				alert("加载失败\n"+data.msg);
				General.closeDialog();
				return;
			}
			var content = data.msg.content;
			var uniqid = data.msg.uniqid;
			var mod = $('<div class="mod" data-uniqid="'+uniqid+'" data-id="'+id+'" data-page-id="'+page_id+'" data-name="'+tag+'">'+content+'</div>');
			if(window.prevElm==null){
				window.base_add_btn.after(mod);
				base_add_btn.remove();
			}else{
				window.prevElm.after(mod);
			}
			addMask(mod);
			General.closeDialog();
		}, "json");
	}
}

function addMask(obj){
	var modMask = $('#mod_mask').clone();
	modMask.removeAttr('id');
	modMask.attr('class','mod_mask');
	var w = $(obj).width();
	var h = $(obj).height();
	modMask.css({width:w,height:h});
	$(obj).css('position','relative').append(modMask);
}

function removeMod(mod,callback){
	if(confirm('确定删除该模块(挂件)吗?该操作将同时删除模块数据')){
		var page_id = mod.attr('data-page-id'),
			widget_id = mod.attr('data-id'),
			uniqid = mod.attr('data-uniqid'),
			name = mod.attr('data-name');
		var delUrl = '/tplConfig/configWidget/delete?uniqid='+uniqid+'&widget_id='+widget_id;
		$.getJSON(delUrl,function(result){
			alert(result.msg);
			if(result.success){
				mod.remove();
				callback();
			}
		});
		
		$('#config-contail').hide();
	}
}

function config(mod){
	var page_id = mod.attr('data-page-id'),
	widget_id = mod.attr('data-id'),
	uniqid = mod.attr('data-uniqid'),
	name = mod.attr('data-name');
	var configUrl = '/tplConfig/configWidget?page_id='+page_id+'&uniqid='+uniqid+'&name='+name+'&widget_id='+widget_id+'&theme='+THEME;
	$.getJSON(configUrl,function(data){
		if(data.error){
			alert(data.msg);
			return;
		}
		var configContail = $('#config-contail'),
		title = configContail.find('.mod-name'),
		formContail = configContail.find('.config-form form');
		title.text(data.msg.name);
		var  $bodyTarget=formContail.html('').append('<input type="hidden" name="page_id" value="'+page_id+'"/>').append('<input type="hidden" name="uniqid" value="'+uniqid+'" />').append('<input type="hidden" name="name" value="'+name+'" />').append('<input type="hidden" name="theme" value="'+THEME+'" />').append('<input type="hidden" name="widget_id" value="'+widget_id+'" />').append(data.msg.content);
		//渲染一些通用前段组件 fei 2015-10-15
		AutoRenderWebCompent.init($bodyTarget);
		configContail.removeClass('hide').show();
	})
}

$(function(){
	$('.pages a').click(function(e){
		$('.pages a').removeClass('active');
		$(this).addClass('active');
	});
	$('#page_view_frame').attr('src',$('.pages li').eq(0).find('a').attr('href'));
})
